/**
 * @author:albert
 */

package com.bkbw.live.battle.database.bean;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.TreeMap;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class TableTemplate<K, T> {
//	private static TableTemplate instance;
//	public static <T> TableTemplate<T> getInstance() {
//		if (instance == null) {
//			instance = new TableTemplate<T>();
//		}
//		return instance;
//	}
	
	private TreeMap<K, T> table = new TreeMap<K, T>();
	private String keyOfTable;
	private Class<T> clazz;
	
	public Class<T> getClazz() {
		return clazz;
	}
	
	public TableTemplate(String jsonString, String key, Class<T> clazz){
		this.clazz = clazz;
		keyOfTable = key;
		String getKey = "get" + key;
		JSONArray jsonArray = JSONArray.fromObject(jsonString);
		init(jsonArray, getKey);
	}
	
	public TableTemplate(JSONArray jsonArray, String key, Class<T> clazz){
		this.clazz = clazz;
		keyOfTable = key;
		String getKey = "get" + key;
		init(jsonArray, getKey);
	}
	
	public TableTemplate(JSONArray jsonArray, String key) {
		doGetClass();
		init(jsonArray, key);
	}
	
	public TableTemplate() {
		doGetClass();
	}
	
	
	void doGetClass() {
		// 在类中定义clazz就能正确获取其类型，但是在init函数栈中定义就不行，貌似是一个叫泛型擦除的东东在影响着
        Type genType = this.getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        this.clazz = (Class<T>) params[0];
    }
	
	public void merge(TableTemplate<K, T> m) {
		TreeMap<K, T> tree = m.getTable();
		table.putAll(tree);
	}
	
	public boolean init(JSONArray jsonArray, String key) {
		try {
			
			
			java.lang.reflect.Method m = clazz.getMethod(key);
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				// jsonobject.tobean 默认的json数据为{"id":1,"birthOfYear":1999}，key是小写的驼峰，对应的bean为getId,getBirthOfYear
				// 如果传递过来的是大写，比如{"Id":1,"BirthOfYear":1999}则会无法识别。处理方法有两种
				// 1 把首字母转为小写
				// 2 加入jsonconfig，在config中过滤首字母为小写
				/*
				JsonConfig config = new JsonConfig();
		        config.setJavaIdentifierTransformer(new JavaIdentifierTransformer() {
		            @Override
		            public String transformToJavaIdentifier(String str) {
		                char[] chars = str.toCharArray();
		                chars[0] = Character.toLowerCase(chars[0]);
		                return new String(chars);
		            }
		        });
	        	config.setRootClass(XxBean.class);	
				 */
				T bean = (T)JSONObject.toBean(jsonObject, clazz);
			    K keyInt = (K)m.invoke(bean,null);
			    //System.out.println(bean);
				table.put(keyInt, bean);
			}
			return true;
		}
		catch (Exception e){
			e.printStackTrace();
			return false;
		}
	}
	
	public T getBeanByKey(K key) {
		if (table.containsKey(key)){
			return table.get(key);
		}
		return null;
	}
	
	public TreeMap<K, T> getTable() {
		return table;
	}
	
	@Override
	public String toString() {
		String ret = "";
		for (K key : table.keySet()) {
			ret += table.get(key).toString();
			ret += "\n";
		}
		return ret;
	}
	
}
